<template>
  <div class="w-hull h-full">
    <!-- Preloader Start -->
    <div class="preloader">
      <img src="assets/images/preloader.svg" alt="preloader" />
    </div>
    <!-- Preloader End -->
    <header class="header can-sticky">
      <div class="container">
        <div class="row">
          <div class="col-12">
            <div class="inner">
              <!-- Logo -->
              <div class="logo">
                <a class="d-flex h-100">
                  <img src="/assets/images/logo-3.png" alt="logo" class="image-fit-contain" />
                </a>
              </div>
              <!-- Logo -->
              <!-- Nav -->
              <TheNavigation :class="['navigation', { open: isMenuOpen }]" />
              <!-- Nav -->
              <MobileNav v-model="isMenuOpen" />
            </div>
          </div>
        </div>
      </div>
    </header>
    <!-- <div class="banner">
      <div class="banner_slider">
        <div
          class="slide-item banner_image"
          :style="{ backgroundImage: `url(${banner_1})` }"
        >
          <div class="banner_text">
            <div class="container">
              <div class="text_inner">
                <p class="subtitle">领先的实验研究平台</p>
                <h1 class="title">
                  深入探索前沿科技的实验室研究<br />
                  实验
                </h1>
              </div>
            </div>
          </div>
        </div>
        <div
          class="slide-item banner_image"
          :style="{ backgroundImage: `url(${banner_2})` }"
        >
          <div class="banner_text">
            <div class="container">
              <div class="text_inner">
                <p class="subtitle">领先的实验研究平台</p>
                <h1 class="title">
                  深入探索前沿科技的实验室研究<br />
                  实验
                </h1>
              </div>
            </div>
          </div>
        </div>
        <div
          class="slide-item banner_image"
          :style="{ backgroundImage: `url(${banner_3})` }"
        >
          <div class="banner_text">
            <div class="container">
              <div class="text_inner">
                <p class="subtitle">领先的实验研究平台</p>
                <h1 class="title">
                  深入探索前沿科技的实验室研究<br />
                  实验
                </h1>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="container">
        <div class="row">
          <div class="col-12">
            <div class="dots_counts">
              <div class="slider-count">
                <span class="current">01</span><small>/3</small>
              </div>
              <div class="slick-slider-dots"></div>
            </div>
          </div>
        </div>
      </div>
    </div> -->

    <div class="banner" v-if="bannerList && bannerList.length > 0">
      <div class="banner_slider">
        <div v-for="item in bannerList" :key="item.id" class="slide-item banner_image" :style="{ backgroundImage: `url('${item.image_url}')` }">
          <div class="banner_text">
            <div class="container">
              <div class="text_inner">
                <p class="subtitle">{{ item.title }}</p>
                <h3 class="title">
                  {{ item.content }}
                </h3>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="container">
        <div class="row">
          <div class="col-12">
            <div class="dots_counts">
              <div class="slider-count">
                <span class="current">{{ pad2(currentSlide) }}</span>
                <small>/{{ bannerList.length }}</small>
              </div>
              <div class="slick-slider-dots"></div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 科研成果展示 -->
    <section class="section-padding section pb-0">
      <div class="container">
        <div class="section-header text-center">
          <h3 class="title">{{ t("common.achievements") }}</h3>
        </div>
        <div class="row justify-content-center">
          <div v-for="item in researchState.list" :key="item.id" class="col-lg-3 col-md-6">
            <NuxtLink :to="`/detail/${item.id}`" class="service_box style_2 w-full">
              <div class="flex items-center justify-center h-40 overflow-hidden">
                <img :src="item.avatar" :alt="item.title" class="image-fit" />
              </div>
              <h5 class="title h-52px overflow-hidden">{{ item.title }}</h5>
              <p class="text text-clamp-2">{{ item.summary }}</p>
            </NuxtLink>
          </div>
        </div>
        <div class="row">
          <div class="col-12">
            <nav>
              <ul class="pagination">
                <li class="page-item" :class="{ disabled: researchState.current_page === 1 }">
                  <a class="page-link" href="javascript:void(0)" aria-label="Previous" @click.prevent="goTo(researchState.current_page - 1)">
                    <span aria-hidden="true">«</span>
                    <span class="sr-only">Previous</span>
                  </a>
                </li>
                <li v-for="p in pages" :key="String(p)" class="page-item" :class="{ active: p === researchState.current_page, disabled: p === '…' }">
                  <span v-if="p === '…'" class="page-link">…</span>
                  <a v-else class="page-link" href="javascript:void(0)" @click.prevent="goTo(p as number)">{{ p }}</a>
                </li>
                <!-- Next -->
                <li class="page-item" :class="{ disabled: researchState.current_page === totalPages }">
                  <a class="page-link" href="javascript:void(0)" aria-label="Next" @click.prevent="goTo(researchState.current_page + 1)">
                    <span aria-hidden="true">»</span>
                    <span class="sr-only">Next</span>
                  </a>
                </li>
              </ul>
            </nav>
          </div>
        </div>
      </div>
    </section>
    <!-- <section class="section-padding thm-bg-light">
      <div class="container">
        <div class="section-header">
          <h3 class="title">院领导集体</h3>
        </div>
        <div class="row testimonial_slider" v-if="leadList.length">
          <div class="col-12" v-for="item in leadList" :key="item.id">
            <div class="testimonial_item">
              <div class="testimonial_image">
                <img :src="item.avatar" :alt="item.name" class="image-fit" />
              </div>
              <div class="testimonial_text">
                <h4 class="title">{{ item.name }}</h4>
                <p class="post">{{ item.position }}</p>
                <p class="text">{{ item.content }}</p>
              </div>
            </div>
          </div>
        </div>

        <div v-else class="text-center text-gray-500 py-6">暂无数据</div>
      </div>
    </section> -->
    <section class="section-padding section">
      <div class="container">
        <div class="section-header text-center">
          <h3 class="title">{{ t("common.advisors") }}</h3>
        </div>
        <div class="row">
          <div class="col-lg-3 col-md-6" v-for="item in expertList" :key="item.id">
            <div class="team_block">
              <div class="team_img">
                <img :src="item.avatar" :alt="item.name" class="image-fit" />
              </div>
              <div class="team_caption">
                <h5 class="team_name">
                  <NuxtLink :to="`/expertDetail/${item.id}`">{{ item.name }}</NuxtLink>
                </h5>
                <p class="team_post h-52px overflow-hidden">{{ item.position }}</p>
              </div>
            </div>
          </div>
        </div>
        <div class="text-center mt-4">
          <button v-if="hasMore" class="thm-btn" :disabled="loading" @click="loadMore">
            {{ loading ? "加载中…" : "加载更多" }}
          </button>
          <p v-else class="text-muted">没有更多了</p>
        </div>
      </div>
    </section>
    <!-- 合作机构logo展示 -->
    <section class="section-padding section thm-bg-light">
      <div class="container">
        <div class="section-header text-center">
          <h3 class="title">{{ t("common.partners") }}</h3>
        </div>

        <section aria-label="合作机构" class="text-center">
          <div class="container">
            <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-7 gap-6 sm:gap-8 md:gap-10 items-center justify-items-center">
              <div class="content-img" v-for="item in cooperateList" :key="item.id">
                <a :href="normalizeUrl(item.url)" target="_blank" rel="noopener noreferrer" class="block">
                  <img :src="item.logo" :alt="`${item.name} Logo`" />
                </a>
                <!-- <img v-else :src="item.logo" :alt="`${item.name} Logo`" width="100" height="100" /> -->
              </div>
            </div>
          </div>
        </section>
      </div>
    </section>

    <TheFooter />
    <div class="thm-bg-color-one copyright">
      <div class="container">
        <div class="row">
          <div class="col-12 text-center">
            <p class="mb-0">
              Copyright © <span id="year"></span>.
              <a target="_blank" href="#" title=" 科技创新院" class="text-white">科技创新院</a>
            </p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watch, nextTick, onBeforeUnmount } from "vue";
import TheNavigation from "~/component/TheNavigation.vue";
import TheFooter from "~/component/TheFooter.vue";
import MobileNav from "~/component/MobileNav.vue";
import { getFetchData } from "~/composables/getData";

const { t } = useI18n();
const route = useRoute();
const { public: pub } = useRuntimeConfig();
useSeoMeta({
  title: "首页",
  description: "展示西科院最新科研成果、合作机构与重点资讯，了解我们如何将科学研究转化为产业价值。",
  ogTitle: "西班牙科技创新院｜首页",
  ogDescription: "科研成果与合作机构一站式展示。",
  ogUrl: pub.siteUrl + route.fullPath,
  ogImage: pub.defaultOG,
  robots: "index, follow",
});

// 面包屑（首页通常不需要，但示范留法）
useHead({
  script: [
    {
      type: "application/ld+json",
      children: JSON.stringify({
        "@context": "https://schema.org",
        "@type": "BreadcrumbList",
        itemListElement: [{ "@type": "ListItem", position: 1, name: "首页", item: pub.siteUrl }],
      }),
    },
  ],
});

interface Expert {
  id: number;
  name: string;
  content: string;
  position: string;
  avatar: string;
  status: number;
  sort: number;
  created_at: string;
  updated_at: string;
}

const isMenuOpen = ref(false);

const bannerList = ref<any>([]);

// 获取轮播图
const bannerRes: any = await getFetchData({
  url: "/api/banner_get_list",
});

bannerList.value = bannerRes.data || [];

// 获取院领导
// const leadList = ref<any>([]);

// const leadRes: any = await getFetchData({
//   url: "/api/lead_get_list",
// });
// leadList.value = leadRes.data.data || [];

// 获取专家顾问
const expertList = ref<Expert[]>([]);
const page = ref(1);
const pageSize = 4;
const loading = ref(false);
const hasMore = ref(true);

async function fetchExperts(reset = false) {
  loading.value = true;
  try {
    const res: any = await getFetchData({
      url: "/api/expert_get_list",
      opts: { page_index: page.value, page_limit: pageSize },
      method: "get",
    });

    const list = res.data.data;

    if (reset) expertList.value = [];
    expertList.value = reset ? list : expertList.value.concat(list);

    // 依据 total 判断是否还有更多；没有 total 就用“返回数量 < pageSize”判断
    if (typeof res?.data?.total === "number") {
      const total = res.data.total as number;
      hasMore.value = expertList.value.length < total;
    } else {
      hasMore.value = list.length === pageSize;
    }

    if (hasMore.value) page.value += 1;
  } finally {
    loading.value = false;
  }
}

await fetchExperts(true);

function loadMore() {
  if (!loading.value && hasMore.value) fetchExperts();
}

// 获取合作机构
const cooperateList = ref<any>([]);

const orgRes: any = await getFetchData({
  url: "/api/cooperate_get_list",
});
cooperateList.value = orgRes.data.data || [];

// 获取科研成果
const researchList = ref<any>([]);
const researchState = reactive({
  list: [] as any[],
  page_index: 1,
  page_limit: 8,
  loading: false,
  hasMore: true,
  last_page: 1,
  current_page: 1,
  total: 0,
});
const totalPages = computed(() => researchState.last_page || Math.max(1, Math.ceil(researchState.total / (researchState.page_limit || 1))));
// 生成页码（含省略号）
const pages = computed<(number | "…")[]>(() => {
  const total = totalPages.value;
  const curr = researchState.current_page;
  const delta = 2; // 当前页左右各展示几个
  if (total <= 7) return Array.from({ length: total }, (_, i) => i + 1);

  const range = new Set<number>([1, total]);
  for (let i = Math.max(1, curr - delta); i <= Math.min(total, curr + delta); i++) {
    range.add(i);
  }
  const arr = Array.from(range).sort((a, b) => a - b);
  const out: (number | "…")[] = [];
  for (let i = 0; i < arr.length; i++) {
    out.push(arr[i]);
    if (i < arr.length - 1 && arr[i + 1] - arr[i] > 1) out.push("…");
  }
  return out;
});

async function fetchResearc(page_index: number) {
  researchState.loading = true;
  try {
    const res: any = await getFetchData({
      url: "/api/science_get_list",
      opts: { page_index, page_limit: researchState.page_limit, type: 0 },
      method: "get",
    });
    const list = res.data.data;
    researchState.list = list;

    // 依据 total 判断是否还有更多；没有 total 就用“返回数量 < pageSize”判断
    if (typeof res?.data?.total === "number") {
      const total = res.data.total as number;
      researchState.hasMore = researchState.list.length < total;
    } else {
      researchState.hasMore = list.length === researchState.page_limit;
    }

    researchState.last_page = res.data.last_page;
    researchState.current_page = res.data.current_page;
    researchState.total = res.data.total;
  } finally {
    researchState.loading = false;
  }
}

await fetchResearc(researchState.page_index);

async function goTo(page: number) {
  if (page < 1 || page > totalPages.value || page === researchState.current_page) return;
  await fetchResearc(page);
}
// const researchRes: any = await getFetchData({
//   url: "/api/science_get_list",
//   opts: { page_index: 1, page_limit: 8 },
// });
// researchState.list = researchRes.data.data || [];

// 补全协议，避免 href="www.xxx.com" 无法正确跳转
function normalizeUrl(u?: string | null) {
  if (!u) return "#";
  return /^https?:\/\//i.test(u) ? u : `https://${u}`;
}

// // post请求
// const res = await getFetchData({
//   url: "/xxx/getList",
//   opts: {
//     memberLevel: 1,
//     pageNum: 1,
//     pageSize: 10,
//   },
//   method: "post",
// });

const currentSlide = ref(1);

const pad2 = (n: number) => String(n).padStart(2, "0");

let initialized = false;

function initBannerSlick() {
  const $el = $(".banner_slider");
  if (!$el.length || typeof $el.slick !== "function" || initialized) return;
  initialized = true;

  // 先绑定事件，再初始化
  $el
    .on("init", (e, slick) => {
      currentSlide.value = (slick?.currentSlide ?? 0) + 1;
    })
    .on("afterChange", (e, slick, current) => {
      currentSlide.value = (current ?? slick?.currentSlide ?? 0) + 1;
    })
    .slick({
      autoplay: true,
      dots: true,
      arrows: false,
      appendDots: $(".slick-slider-dots"), // 或者 $('.slick-slider-dots')[0]
      dotsClass: "slick-dots container",
    });
}
onMounted(async () => {
  console.log("Component is about to be mounted");
  if (process.client) {
    $(".preloader").addClass("hidden");
    $('[data-popup="tooltip"]').tooltip();
    const stop = watch(
      () => bannerList.value.length,
      async (len) => {
        if (len > 0) {
          await nextTick();
          initBannerSlick();
          stop();
        }
      },
      { immediate: true }
    );
    if (window.$ && $(".testimonial_slider").slick) {
      $(".testimonial_slider").slick({
        autoplay: true,
        dots: true,
        arrows: false,
      });
    }
  }
});

onBeforeUnmount(() => {
  const $el = $(".banner_slider");
  if ($el.length && typeof $el.slick === "function" && initialized) {
    $el.slick("unslick");
    initialized = false;
  }
});

// const { data, pending, error } = await useAsyncData('myData', () =>
//     $fetch('https://api.nbweixin.cn/api/ApiEngine/Run', {
//         method: 'POST',
//         body: {
//             ApiEngineKey: 'aaa'
//         }
//     })
// );

// console.log('data:', data.value);

const text = ref("Hello, Nuxt!");
</script>

<style>
.banner_slider {
  position: relative;
}
/* 移动端 */
@media (max-width: 767px) {
  .banner_slider {
    height: 80vh;
    overflow: hidden;
  }
  .banner_slider .slick-list,
  .banner_slider .slick-track,
  .banner_slider .slick-slide,
  .banner_slider .slick-slide > div,
  .banner_slider .slide-item {
    height: 100%;
  }
  .slide-item.banner_image {
    background: center/cover no-repeat;
  }
}
/* PC 端 */
@media (min-width: 768px) {
  .slide-item.banner_image {
    aspect-ratio: 21/9;
    min-height: 420px;
  }
}
.text-clamp-2 {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
